import md5 from "md5";

export default class TableColumnConfig {
    /**
     * 根据表信息获取MD5值
     * @param columns
     * @param tableName
     */
    static getColumnMd5(columns: any, tableName: string) {
        // 获取columns title
        const titles = columns.map((item: any) => item.title);
        return 'xcsj_column_' + md5(titles.join(',') + '--' + tableName);
    }

    /**
     * 存储表信息
     */
    static setTableInfo(tableName: string, columns: any, realColumns: any): void {
        const data: any = [];
        // 只存储 dataIndex title  show 和 export
        columns.forEach((item: any) => {
            data.push({
                dataIndex: item.dataIndex,
                title: item.title,
                show: item.show,
                export: item.export,
            });
        });
        localStorage.setItem(this.getColumnMd5(realColumns, tableName), JSON.stringify(data));
    }

    /**
     * 获取表信息
     */
    static getTableInfo(columns: any, tableName: string, force = false): any {
        const localMd5 = TableColumnConfig.getColumnMd5(columns, tableName);
        const local = localStorage.getItem(localMd5);
        if (local && !force) {
            const localData = JSON.parse(local);
            return localData.map((item: any) => {
                const find = columns.find((column: any) => column.title === item.title);
                if (find) {
                    return {
                        ...find,
                        ...item,
                    };
                }
                return item;
            });
        } else {
            const currentColumns = columns.map((item: any) => {
                return {
                    ...item,
                    export: true,   // 默认可导出
                    show: true,     // 默认显示
                };
            });
            TableColumnConfig.setTableInfo(localMd5, currentColumns, columns);
            return currentColumns;
        }
    }
}
